package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentLikeDto;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentService;
import com.heima.comment.vo.ApCommentVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApComment apComment = new ApComment();
//        apComment.setId();
        if (user.getUserId() == 0) {
            apComment.setUserId(user.getUserId());
            apComment.setUserName("游客");
            apComment.setImage(null);
        } else {
            ResponseResult<ApUser> responseResult = userFeign.getUserById(user.getUserId());
            ApUser apUser = responseResult.getData();
            apComment.setUserId(user.getUserId());
            apComment.setUserName(apUser.getName());
            apComment.setImage(apUser.getImage());
        }

        apComment.setArticleId(dto.getArticleId());
        apComment.setContent(dto.getContent());
        apComment.setLikes(0);
        apComment.setRepay(0);
        apComment.setCreatedTime(new Date());
        mongoTemplate.save(apComment);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult load(CommentDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据文章id查询
        //根据评论发布时间排序
        //分页时条件是 评论时间<mintime
        if (dto.getSize() == null) {
            dto.setSize(10);
        }

        Query query = new Query(Criteria.where("articleId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()));
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));

        query.limit(dto.getSize());
        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);

        List<ApCommentVo> commentVoList = new ArrayList<>();
        //当前登录人是否对这个评论点赞
        for (ApComment apComment : commentList) {
            ApCommentVo apCommentVo = new ApCommentVo();
            BeanUtils.copyProperties(apComment,apCommentVo);
            if (redisTemplate.hasKey("comment_like_"+user.getUserId()+"_"+apComment.getId())){
                apCommentVo.setOperation(0);
            }else {
                apCommentVo.setOperation(1);
            }
            commentVoList.add(apCommentVo);
        }



        return ResponseResult.okResult(commentVoList);
    }

    @Override
    public ResponseResult like(CommentLikeDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //点赞还是取消点赞
        if (dto.getOperation() == 0) {
            ApCommentLike apCommentLike = new ApCommentLike();
//            apCommentLike.setId(user.getUserId());
            apCommentLike.setUserId(user.getUserId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation(dto.getOperation());   //0点赞  1 取消点赞
            mongoTemplate.save(apCommentLike);

            //还需要修改当前评论的点赞数
            Query query = new Query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes",1);
            mongoTemplate.updateFirst(query,update,ApComment.class);

            //记录到redis中：记录当前登录人是否对这个评论点赞
            redisTemplate.boundValueOps("comment_like_"+user.getUserId()+"_"+dto.getCommentId()).set("");

        }else {
            //把当前用户点赞的数据删除
            mongoTemplate.remove(new Query(Criteria.where("userId").is(user.getUserId()).and("commentId").is(dto.getCommentId())),ApCommentLike.class);

            Query query = new Query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes",-1);
            mongoTemplate.updateFirst(query,update,ApComment.class);

            //取消点赞，删除redis中的小标记
            redisTemplate.delete("comment_like_"+user.getUserId()+"_"+dto.getCommentId());
        }
        return ResponseResult.okResult();
    }
}
